package com.androidTool;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Half;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class InstallAPKUtils {
    //下载成功回调
    public interface Callback{
        public void success(String path);
    }

    /**
     * 下载apk
     * @param context
     * @param downUrl
     * @param callback
     */
    public static  void downLoad(final Context context,String downUrl,Callback callback){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(downUrl);
                    //得到connection对象。
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //设置请求方式
                    connection.setRequestMethod("GET");
                    //连接
                    connection.connect();
                    //得到响应码
                    int responseCode = connection.getResponseCode();
                    if(responseCode == HttpURLConnection.HTTP_OK){
                        //得到响应流
                        InputStream inputStream = connection.getInputStream();
                        try {
                           // File file = new File("data/data/com.example.androidbrowserpro/app.apk");
                            String saveFile= Environment.getDownloadCacheDirectory()+"/app.apk";
                            File file=new File(saveFile);
                            if (file.exists()){
                                file.delete();
                            }
                            file.createNewFile();
                            copyInputStreamToFile(inputStream,file);
                            String path=file.getAbsolutePath();
                            Handler mainHandler = new Handler(Looper.getMainLooper());
                            mainHandler.post(() -> {//到主线程安装。。
                                callback.success(path);
                            });
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            Handler h=new Handler(Looper.getMainLooper());
                            h.post(()->{
                                Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT);
                            });
                        } catch (IOException e) {
                            e.printStackTrace();
                            Handler h=new Handler(Looper.getMainLooper());
                            h.post(()->{
                                Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT);
                            });
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     *  InputStream -> File  保存apk 文件
     * @param inputStream
     * @param file
     * @throws IOException
     */
    private static void copyInputStreamToFile(InputStream inputStream, File file)
            throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            int read;
            byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
            outputStream.close();
            // commons-io
            //IOUtils.copy(inputStream, outputStream);
        }
    }

    /**
     * APK安装
     * @param context
     * @param downloadApk
     */
    public static  void installApk(Context context,String downloadApk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(downloadApk);
        Log.d("TAG","安装路径=="+downloadApk);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName()+".fileprovider", file);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }
}
